package org.jeecg.config;

import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.aspect.annotation.AutoRecordLog;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.*;

/**
 * 扫描日志实体
 * @author gbstart
 * @create 2024-05-30 8:57
 */
@Slf4j
@Configuration
public class EntityScanner implements ApplicationContextAware {
//    @Autowired
//    private EntityManager entityManager;

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    @Autowired
    private RedisUtil redisUtil;

    @PostConstruct
    public void scanEntities() throws IOException, ClassNotFoundException {
        final String BASE_PACKAGE = "org.jeecg.modules.erp";
        final String[] BASE_PACKAGES = new String[]{"org.jeecg.modules.erp","org.jeecg.modules.business",
                "org.jeecg.modules.procurement","org.jeecg.modules.storage","org.jeecg.modules.contract.review"};
        final String RESOURCE_PATTERN = "/**/*.class";
        //spring工具类，可以获取指定路径下的全部类
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        try {
            List<String> tableList = new ArrayList<>();
            List<Resource> list = new ArrayList<>();
            for (String basePackage : BASE_PACKAGES) {
                String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                        ClassUtils.convertClassNameToResourcePath(basePackage) + RESOURCE_PATTERN;
                Resource[] resources = resourcePatternResolver.getResources(pattern);
                List<Resource> resourcess = Arrays.asList(resources);
                list.addAll(resourcess);
            }
            //MetadataReader 的工厂类
            MetadataReaderFactory readerfactory = new CachingMetadataReaderFactory(resourcePatternResolver);
            for (Resource resource : list) {
                //用于读取类信息
                org.springframework.core.type.classreading.MetadataReader reader = readerfactory.getMetadataReader((Resource) resource);
                //扫描到的class
                String classname = reader.getClassMetadata().getClassName();
                Class<?> clazz = Class.forName(classname);

                //判断是否有指定主解
                boolean annotationPresent = clazz.isAnnotationPresent(AutoRecordLog.class);
                if(annotationPresent){
                    Map map = new HashMap();
                    AutoRecordLog annotation = clazz.getAnnotation(AutoRecordLog.class);
                    ApiModel apiAnnotation = clazz.getAnnotation(ApiModel.class);
                    String canonicalName = clazz.getCanonicalName();
                    map.put("clazz",canonicalName);
                    map.put("existParent", annotation.existParent());
                    map.put("parentField",annotation.parentFiled());
                    map.put("parentTable",annotation.parentTable());
                    map.put("tableDes",apiAnnotation.description());
                    String value = clazz.getAnnotation(TableName.class).value();
                    tableList.add(value);
//                    List<CloumnVo> cloumnList = getColMap("tsl_db", value);
//                    if(cloumnList!=null){
//                        String[] ignoreCloumns = annotation.ignoreCloumn();
//                        Iterator<CloumnVo> iterator = cloumnList.iterator();
//                        while (iterator.hasNext()){
//                            CloumnVo vo = iterator.next();
//                            String cloumnName = vo.getCloumnName();
//                            for (String ignoreCloumn : ignoreCloumns) {
//                                if(StrUtil.toCamelCase(cloumnName).equals(ignoreCloumn)){
//                                    iterator.remove();
//                                }
//                            }
//                        }
//                        map.put("cloum",cloumnList);
//                    }
                    redisUtil.set(value, map);
                }
            }
            redisUtil.set("tablelist", tableList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


//    public  List<CloumnVo> getColMap(String db, String table) {
//        PreparedStatement ps = null;
//        ResultSet rs = null;
//        Connection connection = null;
//        try {
//            //获取数据源
//            DataSource dataSource = applicationContext.getBean(DataSource.class);
//            connection = dataSource.getConnection();
//            // 执行sql获取表数据
//            String preSql = "SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? and TABLE_NAME = ?";
//            ps = connection.prepareStatement(preSql);
//            ps.setString(1, db);
//            ps.setString(2, table);
//            rs = ps.executeQuery();
////            Map<String, Colum> map = new HashMap<>(rs.getRow());
//            List<CloumnVo> list = new ArrayList<>();
//            while (rs.next()) {
//                String schema = rs.getString("TABLE_SCHEMA");
//                String tableName = rs.getString("TABLE_NAME");
//                String column = rs.getString("COLUMN_NAME");
//                int idx = rs.getInt("ORDINAL_POSITION");
//                String dataType = rs.getString("DATA_TYPE");
//                if (column != null && idx >= 1) {
//                    list.add(CloumnVo.builder().tableSchema(schema)
//                            .tableName(tableName).cloumnName(column).dataType(dataType).ordinalPosition(idx - 1)
//                            .build());
////                    map.put(column, new Colum(schema, tableName, idx - 1, column, dataType)); // sql的位置从1开始
//                }
//            }
//            ps.close();
//            rs.close();
//            connection.close();
//            return list;
//        } catch (SQLException e) {
//            log.error("load db conf error, db_table={}:{} ", db, table, e);
//        } finally {
//            try {
//                if (ps != null) {
//                    ps.close();
//                }
//                if (rs != null) {
//                    rs.close();
//                }
//                if (connection != null) {
//                    connection.close();
//                }
//            } catch (SQLException e) {
//                throw new RuntimeException(e);
//            }
//
//        }
//        return null;
//    }



}
